class Node {
  data = null;
  next = null;
  constructor(value) {
    this.data = value;
    this.next = null
  }
}


class NodeList {
  head = null;
  size = 0;
  constructor() {
    this.head = null;
    this.size = 0;
  }

  print () {
    let current = this.head;
    while (current) {
      console.log(current.data);
      current = current.next;
    }
  }


  add (data) {
    let current = this.head;
    const node = new Node(data);
    if (!current) {
      this.head = node;
      this.size++;
      return;
    }
    while (current.next) {
      current = current.next;
    }
    current.next = node;
    this.size++;
    return;
  }

  addAt (data, index) {
    // 安全性处理
    if (index < 0 || index > this.size) {
      throw new Error("索引值无效");
    }

    const newNode = new Node(data); // 新创建一个节点
    let current = this.head; // 一开始 current 指向头节点
    let counter = 0; // 计数器，对链表节点进行计数，类似于数组的下标

    // 下面就是插入的操作。插入仍然是分为是否是头节点位置
    if (index === 0) {
      // 在头部插入
      // 插入的新节点会成为新的头节点
      newNode.next = this.head;
      this.head = newNode; // 更新头节点的值
    } else {
      // 链表后面部分插入，需要遍历到指定的位置
      while (current) {
        if (counter === index - 1) {
          // 做插入操作
          newNode.next = current.next;
          current.next = newNode;
          break;
        }
        current = current.next;
        counter++;
      }
    }
    this.size++;
  }

  remove (data) {
    let current = this.head;
    if(current === null){
      return;
    }
    if(data === this.head.data){
    this.head = current.next;
    this.size --;
    return;
    }
    while (current.next) {
      if (data === current.next.data) {
        current.next = current.next.next;
        this.size --;
        return;
      } else {
        current = current.next;
      }
    }

  }

  removeAt(index){
    let current = this.head;
    let pre = null;
    if(!current){
      return;
    }

    let i =0;
    while (current) {
      if(i === index &&  i ==0){
        this.head = current.next;
        this.size --;
        return;
      }else if(i ===  index){
        pre.next = current.next;
        this.size --;
        return
      }else{
        i ++;
        pre = current;
        current  = current.next;
      }
    }
  }

}


let a = new Node(1);
let b = new Node(2);
a.next = b;
let c = new Node(3);
b.next = c;


let list = new NodeList();

list.head = a;

list.size = 3;

list.add(4);

// list.addAt(5, 1);

list.print();

// list.remove(2)
list.removeAt(2)

list.print();
